package root.DNSScheduling;

import java.util.List;
import java.util.ArrayList;

class WeightedDNSLoadBalancer {
    private List<String> serverIPs;
    private List<Integer> weights;
    private int currentIndex;

    public WeightedDNSLoadBalancer() {
        serverIPs = new ArrayList<>();
        weights = new ArrayList<>();

        // 假设有三台服务器，分别有不同的权重
        serverIPs.add("192.168.1.1");  // 权重为 3
        serverIPs.add("192.168.1.2");  // 权重为 1
        serverIPs.add("192.168.1.3");  // 权重为 2
        weights.add(3);
        weights.add(1);
        weights.add(2);
        currentIndex = 0;
    }

    // 返回下一个服务器IP，基于权重的轮询a
    public String getNextServerIP() {
        String serverIP = serverIPs.get(currentIndex);

        // 根据权重，跳过某些服务器
        currentIndex = (currentIndex + 1) % getTotalWeight();
        return serverIP;
    }

    // 计算所有服务器的总权重
    private int getTotalWeight() {
        int totalWeight = 0;
        for (int weight : weights) {
            totalWeight += weight;
        }
        return totalWeight;
    }

    public static void main(String[] args) {
        WeightedDNSLoadBalancer loadBalancer = new WeightedDNSLoadBalancer();

        // 模拟20次DNS解析请求
        for (int i = 0; i < 20; i++) {
            System.out.println("DNS解析结果: " + loadBalancer.getNextServerIP());
        }
    }
}
